import React, { Component } from 'react'
import { Input, Table, Button, Modal, Form, Select, Popconfirm, message } from 'antd';
import { UserAddOutlined } from '@ant-design/icons';
import axios from '../../axios/request'

const { Search } = Input;

export default class Users extends Component {


  error = (msg) => {
    message.error(msg);
  };

  state = {
    userArr: '',//所有用户信息
    selectedRowKeys: [], // 选中此处可配置默认列
    visible: false,
    confirmLoading: false,
    modalText: 'Content of the modal',
    userInfo: { //收集添加用户的信息
      userName: '',
      phone: '',
      password: '',
      powerid: '',
      id: ''
    },
    msg: '',  //添加或编辑
    placeholder: { //input默认显示
      userName: '',
      phone: '',
      password: '',
      powerid: ''
    },
  }


  showModal = () => {
    this.setState({
      visible: true,
      userInfo: {},
      msg: '添加',
      placeholder: {}
    })
  };

  handleOk = () => {
    this.setState({
      modalText: 'The modal will be closed after two seconds',
      confirmLoading: true,
    })

    setTimeout(() => {
      let { userName, phone, password, powerid, id } = this.state.userInfo

      if (this.state.msg === '添加') {
        if (!isNaN(Number(phone)) && phone.trim().length === 11) {
          if (userName.trim().length < 10 && !isNaN(Number(phone)) && password.trim() !== undefined && powerid !== undefined) {
            console.log(userName, phone, password, powerid);
            axios({
              url: '/v1/users/add',
              method: 'POST',
              headers: {
                'isLoading': true
              },
              data: {
                phone, password, powerid,
                name: userName
              }
            }).then(result => {
              console.log(result);
              this.getUserData()
            })
          } else {
            this.error('输入不能为空')
          }
        } else {
          this.error('请输入正确的号码')
        }
      }

      if (this.state.msg === '编辑') {

        console.log(userName, phone, password, powerid, id);

        console.log('编辑');
        if (powerid !== '选择权限') {
          axios({
            url: '/v1/users/update',
            method: 'POST',
            headers: {
              'isLoading': true
            },
            data: {
              phone, password, powerid,
              name: userName,
              id
            }
          }).then(result => {

            this.getUserData()

          }).catch(err => {
            this.error(err)
          })
        } else {
          this.error('设置您的权限')
        }

      } else {

      }

      this.setState({
        visible: false,
        confirmLoading: false,
        userInfo: {},
        placeholder: {}
      })


    }, 2000);
  };

  handleCancel = () => {
    this.setState({
      visible: false
    })
  };

  getUserData = () => {
    axios({
      url: '/v1/users/getall',
      method: 'GET',
      headers: {
        'isLoading': true
      },
    }).then(data => {
      //保存所有用户信息
      let userArr = data.data.data
      userArr.forEach((item) => {
        if (item.powerid === 1) {
          item.powerid = '超级管理员'
        } else if (item.powerid === 2) {
          item.powerid = '教职老师'
        } else if (item.powerid === 3) {
          item.powerid = '就业老师'
        } else if (item.powerid === 4) {
          item.powerid = '财务管理'
        } else {
          item.powerid = '销售人员'
        }
      })
      userArr.forEach((item, index) => {
        item.key = index + 1
      })


      this.setState({ userArr })
    })

  }

  //挂载后获取数据
  componentDidMount() {
    this.getUserData()
  }


  //搜索框
  onSearch = (val) => {
    let { userArr } = this.state


    let newArr = userArr.filter((item) => {
      return item.name.indexOf(val) !== -1
    })

    this.setState({
      userArr: newArr
    })

    if (val === '') {
      this.getUserData()

    }

  }

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };


  editStudent = (obj) => {
    let { id, name, password, phone, powerid } = obj
    this.setState({
      visible: true,
      msg: '编辑',
      placeholder: {
        userName: name,
        password, phone,
        powerid
      },
      userInfo: {
        userName: name,
        password, phone, powerid: '选择权限',
        id
      }

    })
  }
  //删除用户
  deleteUser = ({ phone }) => {
    console.log(phone);
    axios({
      url: '/v1/users/delete',
      method: 'POST',
      headers: {
        'isLoading': true
      },
      data: {
        phone
      }
    }).then(result => {
      this.getUserData()
      console.log(result);
    })
  }


  columns = [
    {
      title: 'ID',
      dataIndex: 'key',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '电话',
      dataIndex: 'phone',
    },
    {
      title: '密码',
      dataIndex: 'password',
    },
    {
      title: '权限',
      dataIndex: 'powerid',
    },
    {
      title: '操作',
      dataIndex: '',
      key: 'x',
      render: (obj) => <><Button onClick={() => this.editStudent(obj)} type="primary">编辑</Button> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <Popconfirm onConfirm={() => this.deleteUser(obj)} title="确认删除该用户？" okText="Yes" cancelText="No">
          <Button type="primary" danger>删除</Button>
        </Popconfirm>
      </>


    },
  ];


  handleChange = (value) => {
    let { userInfo } = this.state

    this.setState({
      userInfo: {
        ...userInfo,
        powerid: value
      }
    })
  }
  getFormValue = (name, e) => {
    let { userInfo } = this.state

    this.setState({
      userInfo: {
        ...userInfo,
        [name]: e.target.value
      }
    })

  }



  render() {
    const { selectedRowKeys, visible, confirmLoading, userInfo, msg, placeholder } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      selections: [
        Table.SELECTION_ALL,
        Table.SELECTION_INVERT,
        Table.SELECTION_NONE,
        {
          key: 'odd',
          text: 'Select Odd Row',
          onSelect: changableRowKeys => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changableRowKeys.filter((key, index) => {
              if (index % 2 !== 0) {
                return false;
              }
              return true;
            });
            this.setState({ selectedRowKeys: newSelectedRowKeys });
          },
        },
        {
          key: 'even',
          text: 'Select Even Row',
          onSelect: changableRowKeys => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changableRowKeys.filter((key, index) => {
              if (index % 2 !== 0) {
                return true;
              }
              return false;
            });
            this.setState({ selectedRowKeys: newSelectedRowKeys });
          },
        },
      ],
    };







    return (
      <>


        <Search placeholder="搜索用户姓名" allowClear onSearch={this.onSearch} style={{ width: 400 }} />

        <Button type="primary" onClick={this.showModal} style={{ marginLeft: '30px' }} icon={<UserAddOutlined />}>
          添加用户
        </Button>

        <Modal
          title={`${msg}用户信息`}
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={this.handleCancel}
        >

          <Form
            layout={"horizontal"}
            initialValues={{
              layout: "horizontal",
            }}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 17 }}
          >
            <Form.Item label="姓名">
              <Input placeholder={placeholder.userName ? placeholder.userName : '请输入用户姓名'} value={userInfo.userName} onChange={(e) => this.getFormValue('userName', e)} />
            </Form.Item>
            <Form.Item label="电话">
              <Input placeholder={placeholder.phone ? placeholder.phone : '请输入用户电话'} value={userInfo.phone} onChange={(e) => this.getFormValue('phone', e)} />
            </Form.Item>
            <Form.Item label="密码">
              <Input placeholder={placeholder.password ? placeholder.password : '请输入用户密码'} value={userInfo.password} onChange={(e) => this.getFormValue('password', e)} />
            </Form.Item>
            <Form.Item label="权限">
              <Select defaultValue='选择权限' onChange={this.handleChange} value={userInfo.powerid} >
                <Select.Option value="2">教职老师</Select.Option>
                <Select.Option value="3">财务管理</Select.Option>
                <Select.Option value="4">就业老师</Select.Option>
                <Select.Option value="5">销售人员</Select.Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>


        <Table rowSelection={rowSelection} columns={this.columns} dataSource={this.state.userArr} ></Table>
      </>
    )
  }
}
